import React from 'react';
import { is_empty, Info, KDlg, KFind, obj_int, Dlg, ck_empty, obj_str, loc, ck_int, useKForm, KInput } from 'sui';
import { User } from 'cache';

const get_col = (props) => {
    const tmp = props.col;
    if (is_empty(tmp)) {
        return null;
    }

    const ret = [];

    tmp.forEach(d => {
        const t = d.sn;
        if (t === "sn" || t === "dnum") {
            ret.push(d);
        }
    });

    return ret;
};

const DlgBuy = ({ open, setOpen, hcmd, data, col, supply }) => {
    const form = useKForm();

    const hok = () => {
        const ck = {
            pnum : v => ck_int(v),
        };

        if (supply) {
            ck["supply"] = v => ck_empty(v);
        }

        if (form.isErr(ck)) {
            return;
        }

        const cmd = {
            ...data,
            pnum: obj_int(form.value, "pnum"),
            tech: obj_str(data, "code"),
            techname: obj_str(data, "name"),
            pname: User.uName(),
            kind: "part",
        };

        if (supply) {
            cmd["supply"] = form.get("supply");
        }

        setOpen(false);
        hcmd(cmd);
    };

    const getSupply = () => {
        if (!supply) {
            return null;
        }

        return <KFind label={loc("l_739")} name="supply" form={form} list={supply}/>;
    };

    return (
        <Dlg open={open} hcancel={() => setOpen(false)} hcmd={hok} title={loc("l_552")}>
            <Info data={data} col={get_col({ col: col })} hl={["dnum"]}/>
            <KInput label={loc("l_126")} form={form} name="pnum"/>
            {getSupply()}
        </Dlg>
    );
};

const DlgVal = (props) => {
    const form = useKForm();

    const ck = {
        num : v => {
            const e = ck_int(v);
            if (e) {
                return e;
            }

            const n = parseInt(v, 10);
            const dnum = obj_int(props.data, "dnum");
            if (n > dnum) {
                return loc("l_707");
            }

            return null;
        }
    };

    return (
        <KDlg {...props} title={loc("l_741")} ck={ck} form={form}>
            <Info data={props.data} col={get_col(props)} hl={["dnum"]}/>
            <KInput label={loc("l_126")} form={form} name="num"/>
        </KDlg>
    );
};

const DlgNum = (props) => {
    const form = useKForm(props.data);

    const ck = {
        dnum: v => ck_int(v),
    };

    return (
        <KDlg {...props} title={loc("l_740")} ck={ck} form={form}>
            <Info data={props.data} col={get_col(props)} hl={["dnum"]}/>
            <KInput label={loc("l_127")} form={form} name="dnum"/>
        </KDlg>
    );
};

export {DlgNum, DlgVal, DlgBuy};
